package cc.z8g.browser.html

import android.app.Activity
import cc.z8g.browser.BrowserApp
import cc.z8g.browser.R
import cc.z8g.browser.database.history.HistoryDAO
import cc.z8g.browser.utils.ThemeUtils
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Single
import java.io.File
import java.util.Collections

/**
 * Factory for the history page.
 */
class HistoryFactory(private val activity: Activity) : AbsListPageFactory() {

    private fun Int.toColor(): String {
        val string = Integer.toHexString(this)

        return string.substring(2) + string.substring(0, 2)
    }

    override fun buildPage(): Single<String> = TODO()
    override fun getTemplateFilePath(): String = "html/list.html"

    override fun createPageFile(): File = File(BrowserApp.getApplication().filesDir, HISTORY_FILE_NAME)
    override fun assignTitle(): String = BrowserApp.getApplication().getString(R.string.action_history)
    override fun assignBoxBgColor(): String = ""
    override fun assignBoxTxtColor(): String = ""
    override fun assignBodyBgColor(): String = ThemeUtils.getColor(activity, R.attr.colorPrimary).toColor()

    override fun assignDividerColor(): String = ThemeUtils.getColor(activity, R.attr.autoCompleteBackgroundColor).toColor()

    override fun assignTitleColor(): String = ThemeUtils.getColor(activity, R.attr.autoCompleteTitleColor).toColor()

    override fun assignSubTitleColor(): String = ThemeUtils.getColor(activity, R.attr.autoCompleteUrlColor).toColor()

    override fun assignList(): MutableList<Item> {
        val historyList = HistoryDAO.getImpl().lastHundredVisitedHistoryEntries().blockingGet()
        if (historyList.isEmpty()) {
            return Collections.emptyList()
        }
        val list = ArrayList<Item>(historyList.size);
        historyList.forEach {
            list.add(Item(it.url, it.url, it.title, ""))
        }
        return list
    }

    /**
     * Use this observable to immediately delete the history page. This will clear the cached
     * history page that was stored on file.
     *
     * @return a completable that deletes the history page when subscribed to.
     */
    fun deleteHistoryPage(): Completable = Completable.fromAction {
        with(createPageFile()) {
            if (exists()) {
                delete()
            }
        }
    }
}
